-- UISuperiorBonusTip
-- Created by cheny3 Dec/15/2015
-- 奖励提示

UISuperiorBonusTip = class("UISuperiorBonusTip", function()
    return cc.Layer:create();
end);

function UISuperiorBonusTip.create(title, desc, value, bonusList, okText, okFunc, extraPara)
    return UISuperiorBonusTip.new(title, desc, value, bonusList, okText, okFunc, extraPara);
end

-- 内部函数声明
local resize;

-- 需要修正高度的物品集合
local needFixPosYItems = {};

-- 构造函数
function UISuperiorBonusTip:ctor(title, desc, value, bonusList, okText, okFunc, extraPara)
    self:setName("UISuperiorBonusTip");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/market/SuperiorBonusTip.csb");
    self:addChild(node);
    self.node = node;

    -- 参数
    self.title = title;
    self.desc = desc;
    self.value = value;
    self.okText = okText;
    self.okFunc = okFunc;
    self.extraPara = extraPara;
    self.bonusList = bonusList;

    self:setLocalZOrder(UIMgr.BONUS_NOTIFY_ZORDER + 1);

    -- 注册点击事件
    self:registerTouchEvent();

    -- 注册事件回调
    self:registerEventCallback();

    -- 重绘
    self:redraw();

    -- 适配
    resize(node);
end

-- 注册事件回调
function UISuperiorBonusTip:registerEventCallback()
    -- 注册完成限时礼包事件
    EventMgr.register("UISuperiorBonusTip", event.ACHIEVE_TIME_GIFT, function(args)
        UIMgr.getCurrentScene():removeFormByName("UISuperiorBonusTip");
    end);

    -- 限时礼包数据刷新
    EventMgr.register("UISuperiorBonusTip", event.USER_INFO_UPDATED, function(args)
        if args == "limit_time_gift" then
            UIMgr.getCurrentScene():removeFormByName("UISuperiorBonusTip");
        end
    end);

    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UISuperiorBonusTip 界面析构清理");
            EventMgr.removeAll("UISuperiorBonusTip");

            local uiform = UIMgr:getCurrentScene():getFormByName("UIMarketMain");
            if uiform then
                local btnBuyGem = findChildByName(uiform.node, "BT/btn_buy_gem");
                if not btnBuyGem:isVisible() then
                    btnBuyGem:setVisible(true);
                end
            end
        elseif eventType == "enter" then
        end
    end);
end

-- 注册点击事件
function UISuperiorBonusTip:registerTouchEvent()
    local BT = findChildByName(self.node, "BT");

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(BT, "btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UISuperiorBonusTip");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);

    local btnOk = findChildByName(self.node, "CT/btn_ok");
    -- 注册确定按钮点击事件
    local function onOkClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 是否有回调函数
            if type(self.okFunc) == "function" then
                AudioM.playFx("button_click");
                self.okFunc();
            end
        end
    end
    btnOk:addTouchEventListener(onOkClick);

    local btnDiscount = findChildByName(self.node, "CT/btn_discount");
    -- 注册确定按钮点击事件
    local function onDiscountClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 是否有回调函数
            if type(self.okFunc) == "function" then
                AudioM.playFx("button_click");
                self.okFunc();
            end
        end
    end
    btnDiscount:addTouchEventListener(onDiscountClick);
end

-- 适配
function resize(node)
    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 绘制充值项
function UISuperiorBonusTip:initBonusItem(child, index, itemWidth)
    local i = index;
    local bonus = self.bonusList[i];

    -- 每日奖励
    if self.extraPara and self.extraPara["dailyBonus"] then
        if table.indexOf(self.extraPara["dailyBonus"], i) ~= -1 then
            local tip = findChildByName(child, "tip");
            tip:loadTexture(getCornerImg("daily_bonus"));
            tip:setVisible(true);
        end
    end

    -- 个数
    local countLabel = findChildByName(child, "count");

    -- 超过千的显示修正
    local numText = tostring(bonus[3]);
    if bonus[3] > 1000 then
        if bonus[3] % 1000 == 0 then
            numText = string.format(getLocStr("thousand_num"), bonus[3] / 1000);
        else
            numText = string.format(getLocStr("thousand_num2"), bonus[3] / 1000);
        end
    end

    countLabel:setVisible(true);
    countLabel:setPositionX(0);
    countLabel:setPositionY(-itemWidth/2 + 5);

    TextStyleM.setTextStyle(countLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, -3);
    local text = "+" .. numText;
    countLabel:setString(text);

    -- 图标
    local name;
    local iconPath;
    local scale = 0.82;
    local offsetY = 0;
    local icon = findChildByName(child, "btn");
    if bonus[1] == 1 then
        -- 是道具， 获取道具图标
        iconPath = getItemIconPath(ItemM.query(bonus[2], "icon"));
        name = ItemM.query(bonus[2], "name");

        if ItemM.query(bonus[2], "type") == ITEM_TYPE_SPELL then
            local itemBg = findChildByName(child, "bg");
            itemBg:setVisible(false);
        end

        -- 以下物品需要修正高度
        if table.indexOf(needFixPosYItems, bonus[2]) ~= -1 then
            offsetY = 5;
        end
    elseif bonus[1] == 2 then
        -- 属性
        local path = FieldsM.query(bonus[2], "icon");
        iconPath = getLargeAttribIconPath(path);
        if path == "gem" or path == "money" then
            scale = 1;
        end

        name = FieldsM.query(bonus[2], "name");
    elseif bonus[1] == 3 then
        -- 英雄
        local classId = tonumber(bonus[2]);
        local fileName = PetM.getDefaultIcon(classId);
        iconPath = getHeroIconPath(tostring(fileName));
        name = PetM.query(classId, "name");
        scale = 0.8;
        offsetY = 5;

        -- 获取初始阶位
        local rank = PetM.query(classId, "init_rank");
        local starLayer = createStarLayer(rank, "images/ui/symbol/star_little.png", "center");

        local rankNode = findChildByName(child, "rank");
        rankNode:removeAllChildren();
        rankNode:addChild(starLayer);
        countLabel:setVisible(false);
    elseif bonus[1] == 8 then
        -- 机器人
        iconPath = getRobotIconPath(SkyRobotM.query(bonus[2], "icon"));
        name = SkyRobotM.query(bonus[2], "name");
    end
    icon:loadTexture(iconPath)
    icon:setTouchEnabled(false);
    icon:setScale(scale);
    icon:setPositionY(icon:getPositionY() + offsetY);

    -- 注册点击事件
    self:clickShowDesc(child, bonus);
end

-- 绘制奖励项
function UISuperiorBonusTip:initRechargeItem(child, itemWidth)
    local icon = findChildByName(child, "btn");

    -- 画图片
    local giftId     = self.extraPara["gift_id"];
    local iconName   = MarketM.queryTimeLimitGift(giftId, "icon_id");
    local countLabel = findChildByName(child, "count");
    local iconPath   = getUIMarketIconPath(iconName);

    child:setPosition(0, child:getPositionY());
    icon:loadTexture(iconPath);

    -- 画数量
    countLabel:setVisible(true);
    countLabel:setPositionX(0);
    countLabel:setPositionY(-itemWidth/2 + 5);
    local goodId = MarketM.queryTimeLimitGift(giftId, "good_id");
    local bonus = MarketM.query(goodId).bonus;

    if type(bonus) == "table" and type(bonus[1][3]) == "number" then
        local num = bonus[1][3];
        TextStyleM.setTextStyle(countLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_ORANGE, true, -3);
        countLabel:setString(num);
    end

        -- 点击处理
    local bg = findChildByName(child, "bg");
    bg:setTouchEnabled(true);
    icon:setTouchEnabled(false);
    bg:addTouchEventListener(function(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            showBonusDesc(bonus, {["rechargeTip"] = true, ["goodsId"] = goodId});
        end
    end);
end

-- 重绘
function UISuperiorBonusTip:redraw()
    -- 设置返回按钮的文本样式
    local btnBack = findChildByName(self.node, "BT/btn_back");
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 设置确认按钮文本样式
    local btnOk = findChildByName(self.node, "CT/btn_ok");
    local btnText = self.okText or getLocStr("btn_text_ok");

    -- 美元符号修改
    btnText = changeDollerCharacter(btnText);

    TextStyleM.setTextStyle(btnOk, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnOk:setTitleText(btnText);

    -- 重绘奖励容器
    self:redrawBonus();

    -- 标题
    local titleNode = findChildByName(self.node, "CT/title_node");
    local descLabel = findChildByName(self.node, "CT/desc");
    local valueNode = findChildByName(self.node, "CT/value_node");
    local btnOk = findChildByName(self.node, "CT/btn_ok");
    local titleLabel = findChildByName(titleNode, "title");
    local subHead = findChildByName(titleNode, "subhead");
    local valueDesc = findChildByName(valueNode, "desc");
    local valueLabel = findChildByName(valueNode, "value");
    local icon = findChildByName(valueNode, "icon");
    local btnDiscount = findChildByName(self.node, "CT/btn_discount");
    local btnOriginal = findChildByName(self.node, "CT/btn_original");
    local valueBg = findChildByName(self.node, "CT/value_bg");

    if self.extraPara and self.extraPara["timeLimitGift"] then
        -- 限时礼包倒计时
        self:redrawTime();

        if self.extraPara["is_taken"] == false then
            self:resetButtons();
        end
    end

    -- 标题
    titleLabel:setString(self.title);
    TextStyleM.setArtWordTitleStyle(titleLabel);

    -- 描述
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    descLabel:setString(self.desc);
    descLabel = applyString(descLabel, self.desc);

    -- 价值
    if self.extraPara and self.extraPara["valueDesc"] then
        valueDesc:setString(self.extraPara["valueDesc"]);
    else
        valueDesc:setString(getLocStr("bonus_value_desc"));
    end

    TextStyleM.setTextStyle(valueLabel, TextStyleM.TEXT_SIZE_LARGE2, TextStyleM.TEXT_COLOR_ORANGE, true, nil, nil, nil, nil, nil, true);
    TextStyleM.setTextStyle(valueDesc, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_ORANGE, true, nil, nil, nil, nil, nil, true);
    if self.extraPara and self.extraPara["valueText"] then
        valueLabel:setString(self.extraPara["valueText"]);
    else
        valueLabel:setString(string.format(getLocStr("percent"), self.value));
    end

    -- 显示ICON
    if self.extraPara and self.extraPara["icon"] then
        icon:loadTexture(self.extraPara["icon"]);
        icon:setPositionX(valueLabel:getPositionX() + getRealContentSize(valueLabel).width / 2 + 50);
        icon:setScale(0.8);
    else
        icon:setVisible(false);
    end

    -- 设置超值额度底图
    valueBg:setOpacity(200);
    valueBg:setScale(1.2);
    valueBg:setPositionX(valueBg:getPositionX() - 15);

    -- 艺术字
    -- convertTextToArtWord(valueDesc, "images/ui/text_mask/text_mask4.png", nil, nil, nil, nil, nil, false);
    -- convertTextToArtWord(valueLabel, "images/ui/text_mask/text_mask4.png", nil, nil, nil, nil, nil, false);

    -- 自适应
    local bonusPanel = findChildByName(self.node, "CT/bonus_panel1");
    local bonusPanel2 = findChildByName(self.node, "CT/bonus_panel2");
    local bg = findChildByName(self.node, "CT/bg");

    local nodeArr = { descLabel, bonusPanel, valueBg, btnOk, btnDiscount};
    local offsetArr = { 35, };
    if #self.bonusList > 3 then
        nodeArr = { descLabel, bonusPanel2, valueBg, btnOk, btnDiscount};
        offsetArr = { 35, nil, 10};
    end
    AlignM.adaptLayout(bg, AlignM.BG_SIZE_COMMON, nodeArr, offsetArr, 100);

    -- 计算标题新位置
    local bgScale = bg:getScaleY();
    local bgHeight = getRealContentSize(bg).height;
    local newPosY = titleNode:getPositionY() * bgScale;
    titleNode:setPositionY(newPosY);

    -- 计算超值额度的位置
    valueDesc:setPosition(valueDesc:getPositionX() + 30, valueBg:getPositionY() + 60);
    if not isFullWidthLang() then
        valueLabel:setPosition(valueLabel:getPositionX(), valueDesc:getPositionY() - 38);
    else
        valueLabel:setPosition(valueLabel:getPositionX() + 30, valueDesc:getPositionY() - 38);
    end

    -- 设置原价按钮的位置
    btnOriginal:setPositionY(btnDiscount:getPositionY());
end

-- 绘制时间回调
function UISuperiorBonusTip:redrawTime()
    local subheadLabel = findChildByName(self.node, "CT/title_node/subhead");
    subheadLabel:setVisible(true);
    TextStyleM.setTextStyle(subheadLabel, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_LIGHT_YELLOW, true, -3);
    local function tick()
        -- 限时礼包倒计时
        local leftTime = GiftM.getLimitGiftLeftTime();
        local timeText;
        local hour = math.floor(leftTime / 3600);
        local minute = math.floor((leftTime - hour * 3600) / 60);
        local second = math.floor(leftTime % 60);
        timeText = string.format(getLocStr("left_time"), hour, minute, second);
        subheadLabel:setString(timeText);

        if leftTime <= 0 then
            -- 请求更新
            Operation.cmd_update_time_limit_gift_info();
            UIMgr.getCurrentScene():removeFormByName("UISuperiorBonusTip");
            return;
        end

        performWithDelay(self, tick, 1);
    end

    tick();
end

-- 重绘奖励容器
function UISuperiorBonusTip:redrawBonus()
    local bonusList = self.bonusList or {};
    local parentNode = findChildByName(self.node, "CT/bonus_panel1/bonus_node");
    local parentNode2 = findChildByName(self.node, "CT/bonus_panel2/bonus_node");

    -- 先清空
    parentNode:removeAllChildren();
    parentNode2:removeAllChildren();

    local item = cc.CSLoader:createNode("layout/equip/equip_item.csb");
    item = replaceNodeWithWidget(item);

    local descLabel = findChildByName(self.node, "CT/desc");

    local itemWidth = 100;
    local gap = 20;
    local lineHeight = 105;
    local widget = ccui.Widget:create();
    local widget2 = ccui.Widget:create();
    local totalWidth = #bonusList * (itemWidth + gap);
    local totalWidth2 = #bonusList * (itemWidth + gap);
    local itemsStr = "";
    local totalCount = self.extraPara["gift_id"] and #bonusList + 1 or #bonusList;
    local msg = "";

    if totalCount > 4 then
        -- 多行修正
        totalWidth = 3 * (itemWidth + gap);
        totalWidth2 = (totalCount - 3) * (itemWidth + gap);
    end

    -- 限时礼包第一项固定显示为充值项，其余项显示为奖励项，充值项直接读表就好
    for i = 1, totalCount do

        -- 初始化位置
        local child = item:clone();
        child:setPositionX((i - 1) * (itemWidth + gap));
        if i > 3 then
            -- 修正第二行的位置
            child:setPositionX((i - 1 - 3) * (itemWidth + gap));
            child:setPositionY(child:getPositionY() - lineHeight);
        end

        -- 画格子
        if self.extraPara["gift_id"] then
            if i == 1 then
                self:initRechargeItem(child, itemWidth);
            else
               self:initBonusItem(child, i - 1, itemWidth);
            end
        else
            self:initBonusItem(child, i, itemWidth);
        end

        if i > 3 then
            widget2:addChild(child);
        else
            widget:addChild(child);
        end

    end

    widget:setPositionX(- totalWidth / 2 + (itemWidth + gap) / 2);
    widget2:setPositionX(- totalWidth2 / 2 + (itemWidth + gap) / 2);
    local bonusPanel = findChildByName(self.node, "CT/bonus_panel1");
    local bonusPanel2 = findChildByName(self.node, "CT/bonus_panel2");
    if totalCount > 3 then
        bonusPanel2:setVisible(true);
        bonusPanel:setVisible(false);
        parentNode2:addChild(widget);
        parentNode2:addChild(widget2);
    else
        bonusPanel2:setVisible(false);
        bonusPanel:setVisible(true);
        parentNode:addChild(widget);
    end
end

-- 点击图标处理
function UISuperiorBonusTip:clickShowDesc(node, bonus)
    -- 点击处理
    local bg = findChildByName(node, "bg");
    bg:setTouchEnabled(true);
    bg:addTouchEventListener(function(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("workshop_material");
            showBonusDesc(bonus);
        end
    end);
end

function UISuperiorBonusTip:resetButtons()
    -- 长按钮隐藏
    local btnOk = findChildByName(self.node, "CT/btn_ok");
    btnOk:setVisible(false);

    -- 打折后的按钮
    local btnDiscount = findChildByName(self.node, "CT/btn_discount");
    local btnText = self.okText or getLocStr("btn_text_ok");

    -- 美元符号修改
    btnText = changeDollerCharacter(btnText);

    TextStyleM.setTextStyle(btnDiscount, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnDiscount:setTitleText(btnText);
    btnDiscount:setVisible(true);

    -- 原价按钮
    local btnOriginal = findChildByName(self.node, "CT/btn_original");
    local btnOriginalText = self.extraPara["original_price"] or getLocStr("btn_text_ok");

    -- 美元符号修改
    btnOriginalText = changeDollerCharacter(btnOriginalText);

    TextStyleM.setTextStyle(btnOriginal, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnOriginal:setTitleText(btnOriginalText);
    btnOriginal:setVisible(true);
    btnOriginal:setBright(false);
    btnOriginal:setTouchEnabled(false);
end